from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.decorators import action
from celery.result import AsyncResult
from django.conf import settings
import logging

logger = logging.getLogger(__name__)

class TaskViewSet(viewsets.ViewSet):
    """
    任务管理视图集
    用于查询异步任务的状态和结果
    """
    
    @action(detail=True, methods=['get'])
    def status(self, request, pk=None):
        """
        获取任务状态
        :param pk: 任务ID
        :return: 任务状态和结果（如果有）
        """
        task_id = pk
        
        try:
            task_result = AsyncResult(task_id)
            logger.info(f"查询任务状态: {task_id}, 当前状态: {task_result.state}")
            
            result = {
                'task_id': task_id,
                'state': task_result.state,
            }
            
            # 如果任务已完成，返回结果
            if task_result.ready():
                if task_result.successful():
                    # 获取任务结果
                    task_output = task_result.get()
                    result['result'] = task_output
                else:
                    # 任务失败，获取异常信息
                    result['error'] = str(task_result.result)
            
            return Response(result)
        
        except Exception as e:
            logger.error(f"查询任务 {task_id} 状态发生错误: {str(e)}")
            return Response({
                'task_id': task_id,
                'state': 'ERROR',
                'error': f"查询任务状态出错: {str(e)}"
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR) 